package cn.chendd.patch.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.TrayIcon;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.RootPaneContainer;
import javax.swing.UIManager;

import org.apache.commons.beanutils.ConstructorUtils;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.View;

import cn.chendd.patch.ui.adapters.TrayIconAdapter;
import cn.chendd.patch.ui.adapters.enums.EnumTabPanel;
import cn.chendd.patch.ui.adapters.enums.FileListPanel;
import cn.chendd.patch.ui.adapters.enums.SetFrameAdapter;
import cn.chendd.patch.ui.adapters.enums.TabPanel;
import cn.chendd.utils.LogUtil;
import cn.chendd.utils.MyImageIcon;

import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

public abstract class MainFrame extends SingleFrameApplication {
	
	public int windowWidth = 860;
	public int windowHeight = 650;
	
	public TrayIcon trayIcon;
	public PopupMenu popup;
	
	@Override
	protected void startup() {
		try {
//			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
//			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike;
//			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencySmallShadow;
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
			BeautyEyeLNFHelper.launchBeautyEyeLNF();
			UIManager.put("RootPane.setupButtonVisible", false);//隐藏设置
//			UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName());
		} catch (Exception e) {
			LogUtil.error("使用BeautyEyeLNF皮肤样式出现错误：" , e);
			try {
				UIManager.setLookAndFeel(WindowsLookAndFeel.class.getName());
			} catch (Exception e2) {
				LogUtil.error("使用windows皮肤样式出现错误：" , e2);
			}
		}
		UIManager.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getPropertyName().equals("lookAndFeel")) {
					configureDefaults();
				}
			}
		});
		View view = getMainView();
		configureDefaults();
		JComponent mainPanel = this.createMainPanel();
		view.setComponent(mainPanel);
		view.setMenuBar(this.createMenuBar());
		this.show(view);
	}

	protected JMenuBar createMenuBar() {
		JMenuBar menuBar = new JMenuBar();
		JMenu fileMenu = new JMenu("文件(F) ");
		JMenu settingMenu = new JMenu("设置(S) ");
		JMenu helpMenu = new JMenu("帮助(H) ");
		Font font = new Font("宋体" , Font.PLAIN , 12);
		fileMenu.setFont(font);
		fileMenu.setMnemonic(KeyEvent.VK_F);
		fileMenu.setIcon(new MyImageIcon("file.png"));
		settingMenu.setIcon(new MyImageIcon("setting.png"));
		settingMenu.setMnemonic(KeyEvent.VK_S);
		helpMenu.setIcon(new MyImageIcon("help.gif"));
		helpMenu.setMnemonic(KeyEvent.VK_H);
		JMenuItem closeItem = new JMenuItem("退出");
		closeItem.setIcon(new MyImageIcon("cancel.png"));
		closeItem.setFont(font);
		
		final JFrame frame = this.getFrame();
		closeItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				closeWindow(frame);
			}
		});
		fileMenu.add(closeItem);
		menuBar.add(fileMenu);
		
		JMenuItem paramSettingItem = new JMenuItem("参数设置");
		paramSettingItem.setIcon(new MyImageIcon("save.gif"));
		paramSettingItem.setFont(font);
		paramSettingItem.addActionListener(new SetFrameAdapter(this));
		settingMenu.add(paramSettingItem);
		menuBar.add(settingMenu);
		
		helpMenu.setFont(font);
		JMenuItem aboutMenuItem = new JMenuItem("关于");
		aboutMenuItem.setIcon(new MyImageIcon("warning.gif"));
		aboutMenuItem.setFont(font);
		aboutMenuItem.setEnabled(false);
		helpMenu.add(aboutMenuItem);
		menuBar.add(helpMenu);
		return menuBar;
	}

	/**
	 * 创建主面板
	 */
	protected JComponent createMainPanel() {
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		//初始化系统托盘和右键菜单
		initMenu();
		//初始化查询条件
		initSearchPanel(mainPanel);
		//添加tab页面
		initTabs(mainPanel);
		//最小化至系统托盘
		getFrame().addWindowListener(new TrayIconAdapter(MainFrame.this));
		return mainPanel;
	}

	private void initMenu(){
		//初始化托盘图标
		popup = new PopupMenu();
		//打开
		MenuItem open = new MenuItem();
		open.setLabel("打开");//打开
		open.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				getFrame().setVisible(true);
				getFrame().setExtendedState(JFrame.NORMAL);
			}
		});
		popup.add(open);
		popup.addSeparator();
		//退出
		MenuItem exit = new MenuItem();
		exit.setLabel("退出");//退出
		exit.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				closeWindow(MainFrame.this.getFrame());
			}
		});
		popup.add(exit);
	}
	
	private void initTabs(JComponent mainPanel) {
		
		JTabbedPane tab = new JTabbedPane();
		EnumTabPanel tabs[] = EnumTabPanel.values();
		for (EnumTabPanel enumTab : tabs) {
			Class<?> tabClass = enumTab.getClazz();
			TabPanel tabPanel = null;
			try {
				tabPanel = (TabPanel) ConstructorUtils.invokeConstructor(tabClass, new Object[]{ MainFrame.this , tab });
				tabPanel.init();
				tab.add(enumTab.getText() , tabPanel);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mainPanel.add(tab , BorderLayout.CENTER);
	}
	
	private void initSearchPanel(JComponent mainPanel) {
		
		final String url = "http://www.chendd.cn";
		JLabel label = new JLabel("<html>&nbsp;&nbsp;<a href=\"" + url + "\">" + url + "</a></html>");
		label.setOpaque(true);
		label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		label.setToolTipText("点击访问");
		label.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent event) {
				Desktop desktop = Desktop.getDesktop();
				try {
					desktop.browse(new URL(url).toURI());
				} catch (Exception e) {
					FileListPanel clazz = new FileListPanel(null , null);
					clazz.new Dialog(5 , "提示" , "打不开你的浏览器！");
				}
			}
			
		});
		label.setForeground(Color.RED);
		mainPanel.add(label, BorderLayout.SOUTH);//底部备注
	}

	public JFrame getFrame() {
		View view = getMainView();
		RootPaneContainer c = (RootPaneContainer) view.getRootPane()
				.getParent();
		return (JFrame) c;
	}

	@Override
	public void show(View view) {
		RootPaneContainer c = (RootPaneContainer) view.getRootPane()
				.getParent();
		JComponent rootPane = c.getRootPane();
		Container root = rootPane.getParent();
		if (root instanceof Window) {
			Window window = (Window) root;
			if (!root.isValid() || root.getWidth() == 0
					|| root.getHeight() == 0) {
				window.pack();
			}
		}
		if (c instanceof JFrame) {
			final JFrame frame = (JFrame) c;
			frame.setSize(new Dimension(windowWidth, windowHeight));
			frame.setTitle("补丁整理自动化");
			frame.setIconImage(new MyImageIcon("logo.png").getImage());
			frame.setAlwaysOnTop(false);
			// frame.setResizable(false);
			frame.setLocationRelativeTo(null);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(WindowEvent e) {
					closeWindow(frame);
				}
			});
		}
		((Window) c).setVisible(true);
	}

	public static void closeWindow(JFrame mainFrame) {
		int returnCode = JOptionPane.showConfirmDialog(mainFrame, "确定是要退出吗?",
				"退出", JOptionPane.YES_NO_OPTION);
		if (returnCode == JOptionPane.OK_OPTION) {
			LogUtil.info("程序退出");
			System.exit(0);
		} else if (mainFrame != null) {
			mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		}
	}

	private void configureDefaults() {

	}
}
